<template>
  <div class="mainsu">
    <div class="main_spac1">
      <div class="main_white padding10">
        <div class="mainor_form batch-wrap">
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="100px"
            id="form"
          >
            <el-form-item label="" prop="date_type" class="wid100 methods">
              <el-select v-model="form.date_type" placeholder="请选择">
                <el-option label="配送日期" value="1"> </el-option>
                <el-option label="下单日期" value="2"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="" prop="establishTime">
              <el-date-picker
                v-model="establishTime"
                type="daterange"
                class="time220 marginLeft5s"
                :editable="false"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :clearable="false"
                :picker-options="pickerOptions"
                @change="dateChange"
              />
            </el-form-item>
            <el-form-item label="用户：" prop="uid">
              <change-user-input
                ref="changeUserInput"
                @sendValue="getUser"
                @clear="clearUid"
                palceholder="用户名称 / 编码"
              ></change-user-input>
            </el-form-item>
            <MainFormBtn @reset="reset" @getSearchFor="getArticleList" :loading="listLoading" :showBtn="false">
              <el-button class="mg-r-6" @click="exportform(1)">导出</el-button>
              <el-button @click="summaryExport">汇总导出</el-button>
            </MainFormBtn>
          </el-form>
          <div>
          </div>
        </div>
        <div class="main_table">
          <el-table
          ref="multipleTable"
          class="mg-t-4"
          v-loading="listLoading"
          :data="list"
          element-loading-text="加载中"
          fit
          highlight-current-row
          :header-cell-class-name="this.$verticaline"
          :height="borderHeight"
          :header-cell-style="tableHeightStyle"
        >
          <el-table-column label="配送日期" prop="day">
            <template slot="header">
              <headerSortArrow
                label="day"
                ref="arrow1"
                @handleSort="handleSort($event, 'arrow1')"
                >配送日期</headerSortArrow
              >
            </template>
            <template slot-scope="scope">{{ scope.row.day }}</template>
          </el-table-column>

          <el-table-column label="配送金额" prop="send_money">
            <template slot-scope="scope">
              {{ scope.row.send_money | twoPlace }}
            </template>
          </el-table-column>
          <el-table-column label="成本金额" prop="cost">
            <template slot-scope="scope">
              {{ scope.row.cost | twoPlace }}
            </template>
          </el-table-column>
          <el-table-column label="利润金额" prop="profit">
            <template slot="header">
              <headerSortArrow
                label="profit"
                ref="arrow2"
                @handleSort="handleSort($event, 'arrow2')"
                >利润金额</headerSortArrow
              >
            </template>
            <template slot-scope="scope">
              {{ scope.row.profit | twoPlace }}
            </template>
          </el-table-column>
          <el-table-column label="利润率" prop="profit_rate">
            <template slot="header">
              <headerSortArrow
                label="profit_rate"
                ref="arrow3"
                @handleSort="handleSort($event, 'arrow3')"
                >利润率</headerSortArrow
              >
            </template>
            <template slot-scope="scope">
              {{ scope.row.profit_rate }}%
            </template>
          </el-table-column>
          <el-table-column
            width="120"
            align="center"
            fixed="right"
            label="管理操作"
          >
            <template slot-scope="scope">
              <el-link type="primary" @click="handleDayProfit(scope.row)">
                订单利润</el-link
              >
            </template>
          </el-table-column>
          </el-table>
        </div>
        <div class="main_page boxdq">
          <div></div>
          <!-- 分页 -->
          <div class="main_page_r">
            <MainPagination
              :current-page="current.page"
              :page-sizes="[20, 30, 50, 100]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              background
              @size-change="(pageSize) => changeLimit(pageSize, 1)"
              @current-change="(page) => changePage(page, 1)"
            />
          </div>
        </div>
      </div>
    </div>
    <!-- 订单利润 -->
    <el-drawer
      class="report_drawer drawer_min900"
      title="订单利润"
      size="50%"
      :visible.sync="goods_drawer"
      direction="rtl"
    >
      <div class="drawer_container">
        <div class="drawer_container_header">
          <div class="heder_left">
            <span>{{ drawer_header_title }}</span>
          </div>
          <div class="header_right">
            <el-button type="primary" @click="exportform(2)">导出</el-button>
          </div>
        </div>
        <div class="drawer_container_main">
          <div class="main_table" style="min-height: 400px">
            <el-table
              ref="multipleTable"
              v-loading="drawer_listLoading"
              :data="drawer_list"
              element-loading-text="加载中"
              fit
              border
              highlight-current-row
              :header-cell-class-name="this.$verticaline"
            >
              <el-table-column label="订单号" prop="order_sn">
                <template slot-scope="scope">{{ scope.row.order_sn }}</template>
              </el-table-column>

              <el-table-column label="配送金额" prop="avg_money">
                <template slot-scope="scope">
                  {{ scope.row.send_money | twoPlace }}
                </template>
              </el-table-column>
              <el-table-column label="退货金额" prop="return_money">
                <template slot-scope="scope">
                  {{ scope.row.return_money | twoPlace }}
                </template>
              </el-table-column>
              <el-table-column label="成本金额" prop="cost">
                <template slot-scope="scope">
                  {{ scope.row.cost | twoPlace }}
                </template>
              </el-table-column>
              <el-table-column label="利润金额" prop="profit">
                <template slot-scope="scope">
                  {{ scope.row.profit | twoPlace }}
                </template>
              </el-table-column>
              <el-table-column label="利润率" prop="profit_rate">
                <template slot-scope="scope">
                  {{ scope.row.profit_rate | twoPlace }}%
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="main_page boxdq">
            <div></div>
            <!-- 分页 -->
            <div class="main_page_r">
              <el-pagination
                :current-page="drawer_current.page"
                :page-sizes="[20, 30, 50, 100]"
                :page-size="drawer_limit"
                layout="total, sizes, prev, pager, next, jumper"
                :total="drawer_totalCount"
                background
                @size-change="(pageSize) => changeLimit(pageSize, 2)"
                @current-change="(page) => changePage(page, 2)"
              />
            </div>
          </div>
        </div>
      </div>
    </el-drawer>
    <el-dialog
      title="汇总导出"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="close"
    >
      <el-form :model="formInline" class="demo-form-inline" label-width="120px">
        <el-form-item label="订单日期：">
          <el-date-picker
            style="width: 220px"
            v-model="formInline.order_dates"
            type="daterange"
            range-separator="至"
            value-format="yyyy-MM-dd"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="用户：">
          <change-user-input
            ref="changeUserInput"
            @sendValue="getUsers"
            @clear="clearUid"
          ></change-user-input>
        </el-form-item>
        <el-form-item label="商品名称：" prop="goods_spu_id">
          <change-goods-input
            ref="changeGoodsInput"
            @clear="
              () => {
                this.formInline.goods_spu_id = '';
              }
            "
            @sendValue="
              (data) => {
                this.formInline.goods_spu_id = data.id;
              }
            "
          ></change-goods-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="dialogexportsale">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mixins } from "@/mixins/index.js";
import {
  get_profitOrder,
  get_profitOrderDetail,
  export_exportProfitOrder,
  export_exportProfitOrderDetail,
  exportLiRunList,
} from "@/api/report/index";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { report_shortcuts } from "@/options/new_dateOption";
import { parseTime, exportMethod, getNowMonth } from "@/utils/index";
import headerSortArrow from "@/views/report/components/headerSortArrow";
import { debounce } from "@/utils/debounce";
export default {
  mixins: [mixins],
  components: {
    headerSortArrow,
  },
  data() {
    return {
      pickerOptions: report_shortcuts,
      exportMethod,
      getNowMonth,
      // 时间
      parseTime,
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      // 列表数据
      list: [],
      listLoading: false,
      // 搜索
      form: {
        start_time: "",
        end_time: "",
        uid: "",
        date_type: "1",
        order_by: "",
        order_type: "", //1升序  2降序
      },
      establishTime: [],
      goods_drawer: false, //商品明细抽屉
      drawer_header_title: "配送日期",
      drawer_list: [],
      drawer_listLoading: false,
      // 分页
      drawer_current: {
        page: 1,
        per_page: 20,
      },
      drawer_limit: 20,
      drawer_totalCount: 1,
      drawer_form: {
        send_time: "",
        date_type: "",
      },

      // 汇总导出的展示与隐藏
      dialogVisible: false,
      formInline: {
        order_date: "",
        order_dates: null,
        user_id: "",
        goods_spu_id: null,
      },
    };
  },
  watch: {
    "form.date_type": {
      handler(val) {
        this.drawer_form.date_type = val;
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    this.getNumerical(225);
    this.establishTime = this.getNowMonth();
    this.get_profitOrder();
  },
  methods: {
    startGetting() {
      this.getArticleList();
    },
    get_profitOrder() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      get_profitOrder(data).then((res) => {
        if (res.errcode == 0) {
          this.list = res.data.list;
          this.totalCount = res.data.total;
        } else {
          this.$message.error(res.errmsg);
        }
        this.listLoading = false;
      });
    },
    // 获取用户
    getUser(data) {
      let uid = data.info.user_id;
      this.form.uid = uid;
      // this.offline_index();
    },
    // 清除用户的uid
    clearUid() {
      this.form.uid = "";
      this.formInline.user_id = "";
    },
    // 重置
    reset() {
      this.$refs["userListFrom"].resetFields();
      this.establishTime = this.getNowMonth();
      if(this.$refs["changeUserInput"]) this.$refs["changeUserInput"].name = "";
      if(this.$refs["changeGoodsInput"]) this.$refs["changeGoodsInput"].name = "";
      this.getArticleList();
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.get_profitOrder();
    },
    // 分页
    changeLimit(pageSize, type) {
      switch (type) {
        case 1:
          this.current.per_page = pageSize;
          this.get_profitOrder();
          break;
        case 2:
          this.drawer_current.per_page = pageSize;
          this.get_profitOrderDetail();
          break;
      }
    },
    changePage(page, type) {
      switch (type) {
        case 1:
          this.current.page = page;
          this.get_profitOrder();
          break;
        case 2:
          this.drawer_current.page = page;
          this.get_profitOrderDetail();
          break;
      }
    },

    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.start_time = this.establishTime[0] ? this.establishTime[0] : "";
      form.end_time = this.establishTime[1] ? this.establishTime[1] : "";
      return form;
    },
    // 排序
    handleSort(data, ref) {
      let arr = ["arrow1", "arrow2", "arrow3"].filter((e) => e != ref);
      arr.map((e) => {
        this.$refs[e].selected = false;
      });
      this.form.order_by = data.label;
      this.form.order_type = data.type;
      this.get_profitOrder();
    },
    // 导出
    exportform(type) {
      switch (type) {
        case 1:
          this.export_exportProfitOrder();
          break;
        case 2:
          this.export_exportProfitOrderDetail();
          break;
      }
    },
    //日报表导出
    export_exportProfitOrder() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form()
      );
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      export_exportProfitOrder(data).then((res) => {
        this.exportMethod(res, "利润报表-日报表", notify);
      });
    },
    // 订单利润导出
    export_exportProfitOrderDetail() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.drawer_form
      );
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      export_exportProfitOrderDetail(data).then((res) => {
        this.exportMethod(res, "利润报表-订单利润", notify);
      });
    },

    dateChange(val) {
      let start = new Date(val[0]).getTime();
      let end = new Date(val[1]).getTime();
      let diff = start - end;
      if (Math.abs(diff) > 3600 * 1000 * 24 * 60) {
        this.$message.warning("选择时间跨度不能超过两个月");
        let time = new Date();
        this.establishTime = [time, time];
      }
      this.get_profitOrder();
    },
    handleDayProfit(row) {
      this.drawer_header_title = row.day;
      this.drawer_form.send_time = row.day;
      this.get_profitOrderDetail();
      this.goods_drawer = true;
    },
    //订单利润
    get_profitOrderDetail() {
      this.drawer_listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.drawer_form,
        this.drawer_current
      );
      get_profitOrderDetail(data).then((res) => {
        if (res.errcode == 0) {
          this.drawer_list = res.data.list;
          this.drawer_totalCount = res.data.total;
          this.drawer_listLoading = false;
        } else {
          this.$message.error(res.errmsg);
        }
      });
      // 获取用户
    },
    getUsers(data) {
      let uid = data.info.user_id;
      this.formInline.user_id = uid;
    },
    // 汇总导出
    summaryExport() {
      this.dialogVisible = true;
    },
    close() {
      this.formInline.order_date = "";
      this.$set(this.formInline, "order_dates", []);
      this.formInline.user_id = "";
      this.$refs["changeUserInput"].name = "";
      this.dialogVisible = false;
    },
    dialogexportsale: debounce(function () {
      if (this.formInline.order_dates.length == 0) {
        this.$message.error("请选择时间");
        return;
      }
      this.formInline.order_date = this.formInline.order_dates.join("_");
      let data = this._.cloneDeep(this.formInline);
      delete data.order_dates;
      let query = this.packageApi(data);
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      exportLiRunList(query).then((res) => {
        this.exportMethod(res, "利润报表-汇总明细", notify);
        setTimeout(() => {
          notify.close();
        }, 2000);
      });
    }, 1000),

    // 封装请求的sign和timeStamp字段
    packageApi(data = {}) {
      let query = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        data
      );
      return query;
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";
.reset {
  background-color: transparent;
  color: #1BA88E;
}
/deep/.el-range-editor--small .el-range-separator {
  top: 0px;
}

.mainsu {
  .mainor_form form {
    width: calc(100% - 300px);
  }
}

// 支付状态
.success {
  color: $green;
}
.unpaid {
  color: $colour_red;
}
// 订单状态
.order0 {
  color: $order_color1;
}
.order1 {
  color: $order_color2;
}
.order2 {
  color: $order_color3;
}
.order4 {
  color: $order_color4;
}

.wid100 {
  width: 100px;
}

.marginLeft5s {
  margin-left: -5px;
}
/deep/.methods .el-input__inner {
  border: none;
}
/deep/ .el-form-item--small.el-form-item {
  margin-bottom: 10px;
}
</style>
